<?php
/**
 * Author: DRERY <rui1642@foxmail.com>
 */
namespace backend\components;

use yii\base\ErrorException;
use yii\base\Object;

class ExcelReader extends Object
{
    private $cellRows = array ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' );
    private $objReader;
    public $filePath;
    public $sheetnames;
    /**
     * @var \PHPExcel
     */
    private $objPHPExcel;

    private $hasTitle = true;
    private $sheetIndex = 0;
    private $fields = [];

    public function init()
    {
        $fileType = \PHPExcel_IOFactory::identify ( $this->filePath );
        $this->objReader = \PHPExcel_IOFactory::createReader ( $fileType );
        if ($this->sheetnames)
            $this->objReader->setLoadSheetsOnly ( $this->sheetnames );
        $this->objPHPExcel = $this->objReader->load ( $this->filePath );
    }

    public function getSheetNames()
    {
        return $this->objPHPExcel->getSheetNames ();
    }

    public function getSheet($index)
    {
        return $this->objPHPExcel->getSheet($index);
    }

    public function hasTitle($flag)
    {
        $this->hasTitle = $flag;
        return $this;
    }

    public function sheetIndex($index)
    {
        $this->sheetIndex = $index;
        return $this;
    }

    public function fields($fields)
    {
        $this->fields = $fields;
        return $this;
    }

    public function parse()
    {
        $sheet = $this->getSheet($this->sheetIndex);
        $rowCount = $sheet->getHighestRow();
        $columnCount = $sheet->getHighestColumn();
        $list = [];
        for ($r = $this->hasTitle ? 2 : 1; $r <= $rowCount; $r++) {
            $item = [];
            for ($c = 'A', $i = 0; $c <= $columnCount; $c++, $i++) {
                $value = $sheet->getCell($c . $r)->getValue();
                if (is_object($value))
                    $value = trim($value->__toString());
                if (!empty($this->fields[$i])) {
                    $item[$this->fields[$i]] = trim($value);
                } else {
                    $item[] = trim($value);
                }
            }
            $list[] = $item;
        }
        return $list;
    }
}